import loading from './index.vue';
import Vue from 'vue'

    const LoadingConstructor = Vue.extend(loading);
    const defaults = {
        text: null,
        fullscreen: true,
        body: false,
        lock: false,
        customClass: ''
    };
    let fullscreenLoading; //全屏弹窗实例
    // 关闭弹窗的方法
    function closeLeave(instance, callback, time = 400, once = false) {
        let called = false;
        const closeLeaveCallback = function () {
            if (called) return;
            called = true;
            if (callback) {
                callback.apply(null, arguments);
            }
        };

        setTimeout(() => {
            closeLeaveCallback();
        }, time + 100);
    };

    LoadingConstructor.prototype.close = function () {
        // 清除实例
        if (this.fullscreen) {
            fullscreenLoading = undefined;
        }
        closeLeave(this, _ => {
            // 结束删除节点
            if (this.$el && this.$el.parentNode) {
                this.$el.parentNode.removeChild(this.$el);
            }
            this.$destroy();
        }, 300);
        this.visible = false;
    };
    let service = (options = {}) => {
        // 合并options
        options = Object.assign({}, defaults, options);
        if (typeof options.target === 'string') {
            options.target = document.querySelector(options.target);
        }
        options.target = options.target || document.body;
        if (options.target !== document.body) {
            options.fullscreen = false;
        } else {
            options.body = true;
        }
        // 全屏的loading只能一个
        if (options.fullscreen && fullscreenLoading) {
            return fullscreenLoading;
        }
        let instance = new LoadingConstructor({
            el: document.createElement('div'),
            data: options
        });
        // 如果不存在 target ，弹窗将直接挂载在body
        let parent = options.body ? document.body : options.target;
        parent.appendChild(instance.$el);
        // 使用setTimeout而不使用nextTick是因为使用nextTick弹窗开始动画无效
        setTimeout(() => {
            instance.visible = true;
        }, 1);
        // 如果是全屏，将实例赋值给 fullscreenLoading
        if (options.fullscreen) {
            fullscreenLoading = instance;
        }
        return instance;
    }
    Vue.prototype.$loading = service
    export default service